/**
 * Created Date: Saturday, July 22nd 2023, 3:40:46 pm
 * Author: CodingGorit
 * -----
 * Last Modified: Sun Jul 23 2023
 * Modified By: CodingGorit
 * -----
 * Copyright © 2019 —— 2023 fmin-courses TP Center All Rights Reserved
 * ------------------------------------
 * Javascript will save your soul!
 */

import fs = require("fs");
import multer from 'multer';
import Utils from "../utils/Utils";


/**
 * base file upload
 */
export const upload = multer({ dest: 'uploads/' });

/**
 * storage on disk
 */
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        if (!fs.existsSync("./uploads")) {
            fs.mkdirSync("./uploads");
        }
        cb(null, './uploads');
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        const originFilename = file.originalname as string;
        const newFileName = file.fieldname + '-' + uniqueSuffix + Utils.getFileSufficName(originFilename);
        cb(null, newFileName);
    }
});

/**
 * upload a file to local storage
 */
export const uploads = multer({ storage: storage });